import { createSlice } from '@reduxjs/toolkit'

const cartSlice = createSlice({
    name: 'cart',
    initialState: {
        cartList: []
    },
    reducers: {
        addCart(state, { payload }) {
            // 判断当前商品在 cartList中是否存在，如果存购买数量 + 1
            let index = state.cartList.findIndex(item => {
                return item.id === payload.id
            })
            if (index === -1) {
                // 不存在新增
                console.log('cart payload: ', payload)
                state.cartList.push({
                    ...payload,
                    buyNum: 1 // 购买数量1
                })
            }else{// 存在
                state.cartList[index].buyNum += 1
            }

        }
    }
})

export const {addCart} = cartSlice.actions;
export default cartSlice.reducer;